package com.sftz.framework.ioc;

import org.nutz.ioc.Ioc;
import org.nutz.ioc.impl.NutIoc;
import org.nutz.ioc.impl.ScopeContext;
import org.nutz.ioc.loader.combo.ComboIocLoader;
import org.nutz.lang.Lang;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.IocProvider;
import org.nutz.mvc.NutConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author   朱晓川
 * @Date	 2017年12月19日 	 
 */
public class CustomIocProvider implements IocProvider {

	private static final Log log = Logs.get();

	// Spring应用上下文环境  
	private static ApplicationContext applicationContext;

	static {
		//不在web.xml中servlet加载的时候指定，是因为要提前加载
		log.info("start loading spring ioc...");
		applicationContext = new ClassPathXmlApplicationContext("classpath:spring-config/applicationContext.xml");
	}

	@Override
	public Ioc create(NutConfig config, String[] args) {
		try {
			//TODO 扩展语法
			for (int i = 0; i < args.length; i++) {
				if (args[i].contains("${main}")) {
					args[i] = args[i].replace("${main}", config.getMainModule().getPackage().getName());
				}
			}
			return new NutIoc(new ComboIocLoader(args), new ScopeContext("app"), "app");
		} catch (ClassNotFoundException e) {
			throw Lang.wrapThrow(e);
		}
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * 获取spring-ioc容器中的对象
	 */
	public static <T> T getBean(String name, Class<T> clazz) {
		return getApplicationContext().getBean(name, clazz);
	}

}
